<script setup lang="tsx">
import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm, z } from '#/adapter/form';
import {
  companyAdd,
  companyCheckNameUnique,
  companyInfo,
  companyUpdate,
} from '#/api/company/manage';
import { addressCodeMapToArray } from '#/utils/address';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { drawerSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认label宽度 px
    labelWidth: 120,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: drawerSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
  fieldMappingTime: [
    [
      'addressMap',
      ['countryCode', 'provinceCode', 'cityCode', 'districtCode'],
      null,
    ],
  ],
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicDrawer, drawerApi] = useVbenDrawer({
  // 在这里更改宽度
  class: 'w-[650px]',
  destroyOnClose: true,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);

    const { id } = drawerApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    formApi.updateSchema([
      {
        fieldName: 'name',
        componentProps: {
          onSelect: handleNameSelect,
        },
        rules: z
          .string({
            required_error: '请选择企业名称',
            invalid_type_error: '请选择企业名称',
          })
          .min(1, { message: '请选择企业名称' })
          .refine(
            async (companyName) => {
              return await companyCheckNameUnique(companyName, id);
            },
            {
              message: '企业名称已存在',
            },
          ),
      },
    ]);

    if (isUpdate.value && id) {
      const record = await companyInfo(id);
      // 处理企业标签
      record.labelIds =
        record.labels?.length > 0 ? record.labels.map((label) => label.id) : [];

      // 转成地址级联组件接收的数据格式
      addressCodeMapToArray(record, 'addressMap');
      await formApi.setValues(record);
    } else {
      // 新增时，通过天眼查查询后选择的公司一定是认证的
      await formApi.setFieldValue('certificationStatus', 1);
    }
    await markInitialized();

    drawerApi.drawerLoading(false);
  },
});

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? companyUpdate(data) : companyAdd(data));
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

async function handleNameSelect(val: string) {
  console.log('选择认证', val);
  // 选择的企业一定是认证的
  await formApi.setFieldValue('certificationStatus', 1);
}
</script>

<template>
  <BasicDrawer :title="title">
    <BasicForm />
  </BasicDrawer>
</template>
